package com.liit.console.controller.front;

import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.liit.console.filter.WebContext;
import com.liit.module.entity.Files;
import com.liit.module.entity.OnlineLink;
import com.liit.module.frame.utils.ConfigUtil;
import com.liit.module.frame.utils.Const;
import com.liit.module.frame.utils.FileUtil;
import com.liit.module.frame.utils.ValidatorUtils;
import com.liit.module.frame.utils.page.Pagination;
import com.liit.module.service.FilesService;
import com.liit.module.service.OnlineLinkService;

/**
 * @author dingweibo
 * @Title: OnlineLinkController.java
 * @Description: 线上购物
 * @date 2015年12月21日
 */
@Controller
@RequestMapping(value = "/onlineLink")
public class OnlineLinkController {

	private Logger logger = Logger.getLogger(getClass());

	@Resource
	OnlineLinkService onlineLinkService;

	@Resource
	FilesService filesService;

	/**
	 * 查询线上购物列表
	 * 
	 * @param product
	 * @param pagination
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/list")
	public String list(OnlineLink onlineLink, Pagination pagination) throws Exception {
		Map<String, Object> result = onlineLinkService.listPage(pagination, onlineLink);
		List<OnlineLink> list = (List<OnlineLink>) result.get("list");
		BeanUtils.copyProperties(result.get("page"), pagination);
		Map<String, Files> imgMap = new HashMap<String, Files>();
		for (OnlineLink ol : list) {
			Files imgLogo = filesService.selectById(ol.getImgLogo());
			imgLogo.setPath(FileUtil.getUrl(imgLogo));
			imgMap.put(ol.getId().toString(), imgLogo);
		}
		WebContext.setAttribute("imgMap", imgMap);
		WebContext.setAttribute("list", list);
		WebContext.setAttribute(Const.PAGINATION, pagination);
		return "/front/onlineLinkList";
	}

	@RequestMapping(value = "/add")
	public String add(Integer id) throws Exception {
		if (id != null) {
			OnlineLink onlineLink = onlineLinkService.selectById(id);
			WebContext.setAttribute("onlineLink", onlineLink);
			WebContext.setAttribute("imgLogoPath", FileUtil.getUrl(filesService.selectById(onlineLink.getImgLogo())));
		}
		return "/front/onlineLinkAdd";
	}

	@RequestMapping("/save")
	public String save(OnlineLink onlineLink, @RequestParam("imgLogoFile") MultipartFile imgLogoFile) {
		try {
			// 上传图片
			String path = ConfigUtil.get("file.upload.path") + Const.UPLOAD_PATH_ONLINE_LINK;
			String newFileName = null;
			int type = 0;
			String fileName = null;
			String ext = null;
			int size = 0;// 图片大小
			String contentType = null;
			Date now = new Date();
			Files filesRecord = null;
			// Logo图
			if (!imgLogoFile.isEmpty()) {
				fileName = imgLogoFile.getOriginalFilename();
				ext = fileName.substring(fileName.lastIndexOf('.') + 1);
				newFileName = UUID.randomUUID().toString() + "." + ext;
				size = (int) imgLogoFile.getSize();
				contentType = imgLogoFile.getContentType();
				File targetFile = new File(path, newFileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				imgLogoFile.transferTo(targetFile);

				filesRecord = new Files();
				// 删除历史图片
				if (onlineLink.getImgLogo() != null) {
					filesRecord.setId(onlineLink.getImgLogo());
					filesRecord.setStatus(Const.FILES_STATUS_DELETE);
					filesService.updateById(filesRecord);
				}

				filesRecord.setPath(Const.UPLOAD_PATH_ONLINE_LINK + newFileName);
				filesRecord.setType(type);
				filesRecord.setName(fileName);
				filesRecord.setExt(ext);
				filesRecord.setSize(size);
				filesRecord.setContentType(contentType);
				filesRecord.setSort(0);
				filesRecord.setStatus(Const.FILES_STATUS_INIT);
				filesRecord.setCreateTime(now);
				// 插入图片并得到Files.id
				onlineLink.setImgLogo(filesService.insertAndReturnPK(filesRecord));
			}

			String message = ValidatorUtils.validate(onlineLink);
			if (StringUtils.isBlank(message)) {
				if (onlineLink.getId() != 0) {
					onlineLinkService.updateById(onlineLink);
				} else {
					onlineLink.setId(onlineLinkService.insertAndReturnPK(onlineLink));
				}
				WebContext.setAttribute(Const.MSG, "保存成功");
				WebContext.setAttribute("imgLogoPath",
						FileUtil.getUrl(filesService.selectById(onlineLink.getImgLogo())));
			} else {
				WebContext.setAttribute(Const.MSG, message);
			}
		} catch (Exception e) {
			logger.error("保存失败", e);
			WebContext.setAttribute(Const.MSG, "保存失败");
		}
		return "/front/onlineLinkAdd";
	}

	@RequestMapping("/delete")
	@ResponseBody
	public Object delete(@RequestParam Integer id) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(Const.STATUS, -1);
		OnlineLink record = onlineLinkService.selectById(id);
		if (record == null) {
			map.put(Const.MSG, "未查到信息");
			return map;
		}
		// 删除图片
		filesService.updateStatusByIds(Arrays.asList(record.getImgLogo()), Const.FILES_STATUS_DELETE);
		// 删除购物平台链接
		onlineLinkService.deleteById(id);
		map.put(Const.STATUS, 0);
		return map;
	}
}
